package com.shanjupay.common.utilbak;


import com.alibaba.fastjson.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * AES工具类
 */
public class AESUtil {

    public static void main(String[] args) {
        try {

            JSONObject requestParams = new JSONObject();

            JSONObject head = new JSONObject();
            head.put("username","1013");
            head.put("pwd", "2K+E3CsJ/1KgVXSiwCkiwQ==");
            head.put("method", "cn.kaer.queryAreaInfo");
            head.put("reqTime", "20211109124030");


            JSONObject body = new JSONObject();
            body.put("otherSchoolId","a123321");
            body.put("otherId","a123321");

            requestParams.put("head",head);
            requestParams.put("body",body);

            String a = encryptToKaer(requestParams.toJSONString(), "ac2b5af840fc11ecb9a20242ac12000f");
            System.out.println("加密结果：" + a);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * AES加密
     *
     * @param plaintext 明文
     * @param Key       密钥
     * @return 该字符串的AES密文值
     */
    public static String AES_Encrypt(Object plaintext, String Key) {
        String PlainText = null;
        try {
            PlainText = plaintext.toString();
            if (Key == null) {
                return null;
            }
            byte[] raw = Key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(PlainText.getBytes("utf-8"));
            String encryptedStr = new String(new BASE64Encoder().encode(encrypted));
            encryptedStr = encryptedStr.replaceAll("[\\s*\t\r]", "");
            return encryptedStr;
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * AES加密
     *
     * @param plaintext 明文
     * @param Key       密钥
     * @param iv        使用CBC模式，需要一个向量iv，可增加加密算法的强度
     * @return 该字符串的AES密文值
     */
    public static String AES_Encrypt(Object plaintext, String Key, String iv) {
        String PlainText = null;
        try {
            PlainText = plaintext.toString();
            if (Key == null) {
                return null;
            }
            byte[] raw = Key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            //向量iv
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
            byte[] encrypted = cipher.doFinal(PlainText.getBytes("utf-8"));
            String encryptedStr = new String(new BASE64Encoder().encode(encrypted)); //此处使用BASE64做转码功能，同时能起到2次加密的作用。
            encryptedStr = encryptedStr.replaceAll("[\\s*\t\r]", "");
            return encryptedStr;
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * AES解密
     *
     * @param cipertext 密文
     * @param Key       密钥
     * @return 该密文的明文
     */
    public static String AES_Decrypt(Object cipertext, String Key) {
        String CipherText = null;
        try {
            CipherText = cipertext.toString();
            // 判断Key是否正确
            if (Key == null) {
                return null;
            }
            byte[] raw = Key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted = new BASE64Decoder().decodeBuffer(CipherText);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * AES解密
     *
     * @param plaintext 密文
     * @param Key       密钥
     * @param iv        使用CBC模式，需要一个向量iv，可增加加密算法的强度
     * @return 该密文的明文
     */
    public static String AES_Decrypt(Object plaintext, String Key, String iv) {
        String CipherText = null;
        try {
            CipherText = plaintext.toString();
            if (Key == null) {
                return null;
            }
            byte[] raw = Key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            //向量iv
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);


            byte[] encrypted = new BASE64Decoder().decodeBuffer(CipherText);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * 针对卡尔平台的AES加密
     * @param data
     * @param key
     * @return
     */
    public static String encryptToKaer(String data, String key) {
        String ivString = key.substring(0, 16);
        // 偏移量
        byte[] iv = ivString.getBytes();
        try {
            Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
            byte[] dataBytes = data.getBytes();
            int length = dataBytes.length;
            // 计算需填充长度

            byte[] plaintext = new byte[length];
            // 填充
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            // 设置偏移量参数
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encryped = cipher.doFinal(plaintext);
            return parseByte2HexStr(encryped).toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}
